package com.haust.community.service;

import com.haust.community.mapper.elasticsearch.DiscussPostRepository;
import com.haust.community.pojo.DiscussPost;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Auther: csp1999
 * @Date: 2020/12/01/9:35
 * @Description: ES操作相关的Service
 */
@Service
public class ElasticSearchService {

    @Autowired
    private DiscussPostRepository discussPostRepository;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    /**
     * 向ES中加入一条帖子数据
     *
     * @param discussPost
     */
    public void saveDiscussPost(DiscussPost discussPost) {
        discussPostRepository.save(discussPost);
    }

    /**
     * 根据id从ES中删除一条帖子数据
     *
     * @param id
     */
    public void deleteDiscussPost(int id) {
        discussPostRepository.deleteById(id);
    }

    /**
     * 搜索帖子
     *
     * @param keyword 关键字
     * @param current 当前页
     * @param limit   每页展示数据的数量
     * @return
     */
    public List<DiscussPost> searchDiscussPost(String keyword, int current, int limit) {

        // 构建查询条件对象
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.multiMatchQuery(keyword, "title", "content"))
                .withSort(SortBuilders.fieldSort("type").order(SortOrder.DESC))// 按照帖子分类排序
                .withSort(SortBuilders.fieldSort("score").order(SortOrder.DESC))// 按照帖子分数排序
                .withSort(SortBuilders.fieldSort("createTime").order(SortOrder.DESC))// 按照帖子发布日期排序
                .withPageable(PageRequest.of(current, limit))// 分页
                .withHighlightFields(// 要高亮显示的字段
                        new HighlightBuilder.Field("title").preTags("<em>").postTags("</em>"),
                        new HighlightBuilder.Field("content").preTags("<em>").postTags("</em>")
                ).build();

        // SearchHit：将搜索到的数据与索的条件对象一起封装
        // SearchHits：容纳多个 SearchHit 的集合
        // 根据查询条件查询，并返回 SearchHits 对象
        SearchHits<DiscussPost> searchHits = elasticsearchRestTemplate.search(searchQuery, DiscussPost.class);

        // 设置一个需要返回的实体类集合
        List<DiscussPost> discussPosts = new ArrayList<>();

        // 遍历返回的内容进行处理
        for (SearchHit<DiscussPost> searchHit : searchHits) {
//            DiscussPost post = new DiscussPost();

            // 高亮内容的map集合
            Map<String, List<String>> highlightFields = searchHit.getHighlightFields();

//            // 帖子id
//            String id = highlightFields.get("id").toString();
//            post.setId(Integer.parseInt(id));
//
//            // 发布帖子的用户id
//            String userId = highlightFields.get("userId").toString();
//            post.setUserId(Integer.parseInt(userId));
//
//            // 帖子标题
//            String title = highlightFields.get("title").toString();
//            post.setTitle(title);
//
//            // 帖子内容
//            String content = highlightFields.get("content").toString();
//            post.setContent(content);
//
//            // 帖子状态
//            String status = highlightFields.get("status").toString();
//            post.setStatus(Integer.parseInt(status));
//
//            // 贴子发布日期
//            String createTime = highlightFields.get("createTime").toString();
//            post.setCreateTime(new Date(Long.parseLong(createTime)));
//
//            // 帖子总评论数
//            String commentCount = highlightFields.get("commentCount").toString();
//            post.setCommentCount(Integer.parseInt(commentCount));
//
//            // 帖子标题高亮显示
//            if (highlightFields.get("title") != null) {
//                post.setTitle(highlightFields.get("title").get(0));
//            }
//
//            HighlightField contentField = hit.getHighlightFields().get("content");
//            if (contentField != null) {
//                post.setContent(contentField.getFragments()[0].toString());
//            }

            System.out.println();
            // 将高亮的内容填充到content中
//            System.out.println("title======"+highlightFields.get("title").toString());
//            System.out.println("content======"+highlightFields.get("content").toString());
//            System.out.println("title0======"+highlightFields.get("title").get(0));
//            System.out.println("content0======"+highlightFields.get("content").get(0));

//            searchHit.getContent().setTitle(highlightFields.get("title") == null ?
//                    searchHit.getContent().getTitle() : highlightFields.get("title").get(0));
//            searchHit.getContent().setTitle(highlightFields.get("content") == null ?
//                    searchHit.getContent().getContent() : highlightFields.get("content").get(0));

            if (highlightFields.get("title") != null) {
                searchHit.getContent().setTitle(highlightFields.get("title").get(0));
            }

            if (highlightFields.get("content") != null) {
                searchHit.getContent().setContent(highlightFields.get("content").get(0));
            }
//            System.out.println("=====================" + searchHit.getContent().getTitle() + "=====================");
//            System.out.println("=====================" + searchHit.getContent().getContent() + "=====================");
            // 放到实体类中
            discussPosts.add(searchHit.getContent());
        }

        return discussPosts;
    }
}
